package com.mi.system.websocket;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;

import java.security.Principal;
import java.util.Objects;

/**
 * WebSocket Server Event Listener
 *
 * @author jin_huaquan
 * @version 1.0
 * @date 2020/2/15 21:45
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class WebSocketEventListener {

    private final SimpUserRegistry userRegistry;

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        Principal user = headerAccessor.getUser();

        log.debug("WebSocket Server Creat New Connect : {}", Objects.isNull(user) ? "unknown" : user.getName());
        log.debug("WebSocket Current Online Count : {}", userRegistry.getUserCount());
    }

    @EventListener
    public void sessionDisconnectEvent(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        Principal user = headerAccessor.getUser();

        log.debug("WebSocket Connection Closed : {}", Objects.isNull(user) ? "unknown" : user.getName());
        log.debug("WebSocket Current Online User Count : {} ", userRegistry.getUserCount());
    }

    @EventListener
    public void handleWebSocketSubscribeListener(SessionSubscribeEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        MessageHeaders messageHeaders = headerAccessor.getMessageHeaders();
        Principal user = headerAccessor.getUser();
        String simpDestination = (String) messageHeaders.get("simpDestination");

        log.debug("WebSocket Get New Subscriber : {} -> {}", Objects.isNull(user) ? "unknown" : user.getName(), simpDestination);
    }
}
